package com.tomatozq163.security.access;

import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.thymeleaf.util.StringUtils;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class MyAccessDecisionVoter implements AccessDecisionVoter<Object> {
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, Object o, Collection<ConfigAttribute> collection) {
        FilterInvocation fi = (FilterInvocation)o;

        //获取所有数据库中url，判断与当前是否匹配
        //如果匹配再判断当前用户是否允许访问该url

        List<String> urls = Arrays.asList("/hello","/user/**","/admin/**");

        List<String> allows = Arrays.asList("/hello","/user/**","/admin/**");

        Boolean exist = false;
        String url = "";

        for (String path : urls) {
            AntPathRequestMatcher matcher =new AntPathRequestMatcher(path);

            if(matcher.matches(fi.getRequest())){
                url = path;
                exist = true;
            }
        }

        if (!StringUtils.isEmpty(url)) {
            if(allows.contains(url)) {
                return ACCESS_GRANTED;
            }
            else{
                return ACCESS_DENIED;
            }
        }

        return ACCESS_ABSTAIN;
    }
}
